/**
 * 安卓白金英雄坛制作组 <br>
 * 文件名：GameMessageHandler.java <br>
 * 创建时间：2015年4月13日 下午6:36:28 <br>
 * 所属项目：GmudEX <br>
 * @author 12548
 */
package lostland.gmud.exv2;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.GetListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.update.BmobUpdateAgent;
import lostland.gmud.exv2.community.GmudUser;
import lostland.gmud.exv2.data.GmudMap;
import lostland.gmud.exv2.data.Room;
import lostland.gmud.exv2.data.SaveData;
import lostland.gmud.exv2.ui.BlankScreen;
import lostland.gmud.exv2.ui.LockedScreen;
import lostland.gmud.exv2.ui.StartScreen;
import lostland.gmud.exv2.ui.meta.CreatingDialog;
import lostland.gmud.exv2.ui.meta.EditNameDialog;
import lostland.gmud.exv2.ui.meta.FeedbackDialog;
import lostland.gmud.exv2.ui.meta.LoginDialog;
import lostland.gmud.exv2.ui.meta.RegisterDialog;
import lostland.gmud.exv2.ui.meta.ResetPasswordDialog;

/**
 * 类名：GameMessageHandler <br>
 * 说明：用来处理一些弹出对话框之类的内容
 *
 * @author 12548
 */
public final class GameMessageHandler extends Handler {

	public static final int MSG_FEEDBACK = 0;
	public static final int MSG_AUTOUPDATE = 1;
	public static final int MSG_RENAME = 2;
	public static final int MSG_CREATE = 4;
	public static final int MSG_QUIT = 9;
	public static final int MSG_QUIT_DIALOG = 10;
	public static final int MSG_REGISTER = 13;
	public static final int MSG_LOGIN = 14;
	public static final int MSG_RESETPASSWORD = 15;
	public static final int MSG_CLOUDSAVE = 17;
	public static final int MSG_CLOUDLOAD = 18;
	public static final int MSG_MARRY = 24;
	public static final int MSG_QIECUO = 25;
	public static final int MSG_SHOWAD = 888;
	public static final int MSG_PAY = 999;


	/*
	 * （非 Javadoc）
	 * @see android.os.Handler#handleMessage(android.os.Message)
	 */
	@Override
	public void handleMessage(Message msg) {
		super.handleMessage(msg);

		switch (msg.what) {
			case MSG_FEEDBACK:
				new FeedbackDialog(Game.getInstance()).show();
				break;

			case MSG_AUTOUPDATE: // 自动更新
				if (Game.autocheckupdate) {
					try {
						BmobUpdateAgent.update(Game.getInstance());
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				break;
			case MSG_RENAME: // 人物改名
				new EditNameDialog(Game.getInstance()).show();
				break;
			case MSG_CREATE:// 创造人物
				StartScreen.flag = false;
				new CreatingDialog().show();
				break;
			case MSG_QUIT:
				new BlankScreen().pushToGame();
				break;
			case MSG_QUIT_DIALOG:// 退出
				new AlertDialog.Builder(Game.getInstance())
						.setTitle(Game.tr(R.string.app_name))
						.setMessage(Game.tr(R.string.exit_hint))
						.setPositiveButton(Game.tr(R.string.yes),
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface arg0, int arg1) {
										new BlankScreen().pushToGame();
									}
								})
						.setNegativeButton(Game.tr(R.string.no),
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
									}
								}).show();
				break;
			case MSG_REGISTER: // 注册
				new RegisterDialog(Game.getInstance()).show();
				break;
			case MSG_LOGIN: // 登录
				new LoginDialog(Game.getInstance()).show();
				break;
			case MSG_RESETPASSWORD: // 重置密码
				new ResetPasswordDialog(Game.getInstance()).show();
				break;

			case MSG_CLOUDSAVE: // 云存档上传
				cloudSave();
				break;

			case MSG_CLOUDLOAD: // 云存档读取
				cloudLoad();
				break;
			case MSG_MARRY: // 新结婚
				Game.propose_process();
				break;
			case MSG_QIECUO: // 新切磋
				Game.qiecuo_process();
				break;
			case MSG_SHOWAD:


				break;
			case MSG_PAY:
				double price = msg.arg1;
				if (Gmud.DEBUG) {
					price *= 0.004;
				}
//				new PaymentDialog(price).show();

				Game.getInstance().callPay(price);

				break;
		}

	}


	/**
	 * 云存档储存
	 */
	protected void cloudSave() {


		final SaveData nsf = SaveData.getInstance();
		final GmudUser user = BmobUser.getCurrentUser(Game.getInstance(), GmudUser.class);
		nsf.username = user.getUsername();
		new LockedScreen("正在上传存档，请稍候......").pushToGame();

		try {

			if (user.getSaveObjectID().trim().equals("")) {

				nsf.save(Game.getInstance(), new SaveListener() {

					@Override
					public void onFailure(int arg0, String arg1) {
						Toast.makeText(Game.getInstance(), "保存失败！" + arg0 + arg1,
								Toast.LENGTH_SHORT).show();
						Game.getInstance().popScreen();
					}

					@Override
					public void onSuccess() {

						user.setSaveObjectID(nsf.getObjectId());

						user.update(Game.getInstance(), new UpdateListener() {

							@Override
							public void onFailure(int arg0, String arg1) {
								Toast.makeText(Game.getInstance(), "保存失败！" + arg0 + arg1,
										Toast.LENGTH_SHORT)
										.show();
								Game.getInstance().popScreen();
							}

							@Override
							public void onSuccess() {
								Toast.makeText(Game.getInstance(), "保存成功！",
										Toast.LENGTH_SHORT).show();
								Game.getInstance().popScreen();
							}
						});
					}
				});

			} else {
				nsf.update(Game.getInstance(), user.getSaveObjectID(),
						new UpdateListener() {

							@Override
							public void onFailure(int arg0, String arg1) {
								Toast.makeText(Game.getInstance(), "更新存档失败！" + arg0 + arg1,
										Toast.LENGTH_SHORT).show();
								Game.getInstance().popScreen();
							}

							@Override
							public void onSuccess() {
								Toast.makeText(Game.getInstance(), "更新存档成功！",
										Toast.LENGTH_SHORT).show();
								Game.getInstance().popScreen();
							}
						});
			}

//			GmudHttp http = new GmudHttp("正在上传存档......");
//			RequestParams pr = new RequestParams();
//
//			pr.addBodyParameter("svid", user.getSaveObjectID().trim());
//			pr.addBodyParameter("mc", new Gson().toJson(nsf.mc));
//
//			http.sendLocked(HttpMethod.POST, GmudHttp.getUrl("Battle/Info/updateSave"), pr, new GmudRequestListener() {
//
//				@Override
//				public void onSucc(ResponseInfo<String> info) {
//					new NotificationScreen("成功").pushToGame();
//					Logger.i(info.result);
//				}
//
//				@Override
//				public void onFail(HttpException error, String msg) {
//					new NotificationScreen("失败").pushToGame();
//					Logger.e(msg);
//				}
//			});
//


		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(Game.getInstance(), "error!", Toast.LENGTH_SHORT).show();
			Game.getInstance().popScreen();
		}
	}


	/**
	 * 云存档读取
	 */
	public static void cloudLoad() {
		BmobQuery<SaveData> q = new BmobQuery<>();
		new LockedScreen("正在下载存档，请稍候......").pushToGame();
		q.getObject(Game.getInstance(), GmudUser.getInstance().getSaveObjectID(),
				new GetListener<SaveData>() {

					@Override
					public void onFailure(int arg0, String arg1) {
						Toast.makeText(Game.getInstance(), "下载失败！" + arg1, Toast.LENGTH_SHORT).show();
						Game.getInstance().popScreen();
					}

					@Override
					public void onSuccess(SaveData arg0) {

						if (arg0.ver < GameConstants.SAVEGAME_VER) {
							Toast.makeText(Game.getInstance(), "存档版本不符！", Toast.LENGTH_SHORT).show();
							Game.getInstance().popScreen();
							return;
						}

						LoadingScreen.loadBasicDatas();

						Gmud.mc = arg0.mc;
						Game.getInstance().oldmc = arg0.oldmc;
						Game.getInstance().data = arg0.data;
						Gmud.mc.refreshItems();
						MapScreen.getInstance().jumpTo(1, 9, 7, Direction.DOWN);
						new Room().after_process();

						Gmud.maps[1].setEvent(10, 7, -1);
						Gmud.maps[1].setWalkable(10, 7, GmudMap.MP_WALKABLE);

						Toast.makeText(Game.getInstance(), "下载成功！", Toast.LENGTH_SHORT).show();
						Game.getInstance().popScreen();
					}
				});
	}

}
